#!/bin/bash

#-------------------------------------------------------
#TITLE:		SVN backup Handle
#AUTHOR:	Zhou Chenhan
#TIME:		2013/08/02
#VERSION:	for CentOS6
#-------------------------------------------------------

#指定SVNBACKUP配置文件
conf_path=/root/svnbak.conf
[ ! -e "$conf_path" ] && echo "config file don't exist!" && exit 1;

#解析配置文件获取nfs_dir
eval $(cat $conf_path  | grep nfs_dir)
[ -z "$nfs_dir" ] && echo "nfs file path don't exist!" && exit 1;

#解析配置文件获取保留几份备份
dele_bak_num=2
eval $(cat $conf_path  | grep dele_bak_num) 
#解析配置文件获取工程路径，以逗号隔开
eval $(cat $conf_path  | grep "project_path")
[ -z "$project_path" ]  && echo "project file path don't exist!" && exit 0;

#定义数组 工程名称 工程路径
declare -a pro 
declare -a pro_path

oldIFS=$IFS
IFS=,
n=0
for list in $project_path
do
    pro[n]=${list##/*/}
    pro_path[n]=$list
    n+=1
done
IFS=$oldIFS

NFSDIR=$nfs_dir

#遍历各个工程文件，并执行备份。
n_pro=0
for project in ${pro[@]}
do
SRCPATH=${pro_path[n_pro]}
DISTPATH=$NFSDIR/$project/`date +\%y%m%d`/ ; 
if [ ! -d "$DISTPATH" ] 
then 
   mkdir -p  $DISTPATH 
   chmod g+s $DISTPATH 
fi 
svnadmin hotcopy $SRCPATH $DISTPATH ; 
#检查上方制作的备份是否可用
ver=`svnadmin verify $DISTPATH 2>>/root/svn_bakup_log && echo $?`
[ "$ver" == "0" ] && printf $project" vertify successd\n\r"
n_pro+=1

#删除过期备份
dir_num=`ls $NFSDIR/$project | awk '{n+=1}END{print n}'`

while [ $dir_num -gt $dele_bak_num ]
do
dele_dir=`ls -l $NFSDIR/$project | awk 'NR>1{ti=$6" "$7" "$8;cmd="date -d \""ti"\" +%s ";cmd|getline time_s;print time_s,$9}' | sort  -k1 -n | head -n1 | awk '{print $2}'`
rm -rf $NFSDIR/$project/$dele_dir
echo "$NFSDIR/$project/$dele_dir has been deleted"
dir_num=`ls $NFSDIR/$project | awk '{n+=1}END{print n}'`
done
done
